import { Navigate, useRoutes, Outlet, useLocation } from "react-router-dom";
import { RouteObject } from "@/routers/interface";
import { store } from "@/redux";

import Login from "@/views/login";
import NoFound from "@/views/errorPage/404"
import NoPermission from "@/views/errorPage/403"
import { LayoutIndex } from "./constant";
import lazyLoad from "./utils/lazyLoad";
import React from "react";

// 导入所有router
const metaRouters = import.meta.glob('./modules/*.tsx', {eager: true});

// 处理路由
export const routerArray: RouteObject[] = [];
Object.keys(metaRouters).forEach((item:string) => {    
    Object.keys(metaRouters[item] as any).forEach((key: any) => {        
        routerArray.push(...(metaRouters[item] as any)[key]);
    });
});

export const rootRouter: RouteObject[] = [
    {
        path: '/',
        element: <Navigate to="/login" />
    },
    {
        path: '/login',
        element: <Login />,
        meta: {
            requiresAuth: false,
            title: "登录",
            key: "login"
        }
    },
    {
        element: <LayoutIndex />,
        meta: {
          title: "Loading"
        },
        children: [
          {
            path: "/loading",
            element: lazyLoad(React.lazy(() => import(`@/views/loading/index`))),
            meta: {
              requiresAuth: true,
              title: "Loading",
              key: "/loading"
            }
          }
        ]
      },
    ...routerArray,
    {
        path: '*',
        element: <Navigate to="/404" />
    },
    {
        path: '/404',
        element: <NoFound />,
        meta: {
            requiresAuth: false,
            title: "404",
            key: "404"
        }
    },
    {
        path: '/403',
        element: <NoFound />,
        meta: {
            requiresAuth: false,
            title: "404",
            key: "403"
        }
    },
]

const Router = () => {
    const routes = useRoutes(rootRouter);
    return routes
}

export default Router;